package com.zodiac.app.gsps.configuration;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

import static com.zodiac.app.gsps.configuration.DataSourcePrimaryConfiguration.REPOSITORY_PACKAGE;

@Configuration
@MapperScan(basePackages = {REPOSITORY_PACKAGE}, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class DataSourcePrimaryConfiguration {
    static final String REPOSITORY_PACKAGE = "com.zodiac.app.gsps.datasource.primary.repository";
    private static final String CONFIGURATION_PREFIX = "datasource.primary";

    @Primary
    @Bean
    @ConfigurationProperties(prefix = CONFIGURATION_PREFIX)
    public DataSource primaryDataSource() {
        return DataSourceHelper.createDataSource();
    }

    @Primary
    @Bean
    public DataSourceTransactionManager primaryTransactionManager() {
        return DataSourceHelper.createDataSourceTransactionManager((primaryDataSource()));
    }

    @Primary
    @Bean
    public SqlSessionFactory primarySqlSessionFactory() {
        return DataSourceHelper.createSqlSessionFactory(primaryDataSource(), "classpath:" + REPOSITORY_PACKAGE.replace(".", "/") + "/**/*.xml");
    }
}
